<template>
  <div class="imageCut">
    <canvas-img ref="canv" :imgUrl="chooseImgSrc" @canvasFile="canvasFile" @close="clearImg"></canvas-img>
    <div class="imageCut-box">
      <div v-if="!canvasSrc" class="imageCut-box-item" @click="chooseImg">
        <div>点击此处选择图片</div>
        <i class="iconfont iconwenjian1"></i>
      </div>
      <div v-if="canvasSrc" class="imageCut-box-img">
        <Image style="flex: 1" :src="canvasSrc"></Image>
        <div class="imageCut-box-img-option">
          <Button @click="cancel">取消</Button>
          <Button @click="canv.canvasToBase64()">裁剪</Button>
        </div>
      </div>
    </div>

    <div class="imageCut-input">
      <input ref="inputFileRef" type="file" @input="getImgUrl" />
    </div>
  </div>
</template>

<script setup lang="ts">
import CanvasImg from '@/components/canvasImg.vue'
import Button from '@/components/button.vue'
import Image from '@/components/Image/index.vue'
import { ref } from 'vue'

const chooseImgSrc = ref<string>('')
const canv = ref<{ showBack: boolean; canvasToBase64: () => void }>({ showBack: false, canvasToBase64: () => {} })
const inputFileRef = ref<HTMLInputElement | null>(null)
const canvasSrc = ref<string>('')

// 选择图片
const chooseImg = () => {
  if (inputFileRef.value) {
    inputFileRef.value.click()
  }
}

// 获取裁剪后的File
const canvasFile = (file: File) => {
  clearImg()
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    const src = reader.result as string
    canvasSrc.value = src
    // 这里的reader.result就是文件的base64了。如果是图片的话，就能够间接放到src中展现了
  }
}

// 清除图片
const clearImg = () => {
  if (inputFileRef.value) {
    inputFileRef.value.value = ''
  }
}

// 获取图片url
const getImgUrl = () => {
  if (inputFileRef.value) {
    const files = inputFileRef.value.files
    if (files?.length) {
      let url = window.webkitURL || window.URL
      chooseImgSrc.value = url.createObjectURL(files[0])
      canv.value.showBack = true
    }
  }
}

// 取消
const cancel = () => {
  canvasSrc.value = ''
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
